<!-- 知识图谱功能 canvas 版本实现 -->
<script>
import { defineComponent, createApp, h } from 'vue';
import GlobalCard from '@/components/GlobalCard/global-card.vue';
let GraphIns = null;
let GlobalOBJ = {};
export default defineComponent({
  name: "knowledge-over-lay",
  components: {
    GlobalCard,
  },
  setup() {
  },
  props: {
  },
  data() {
    return {
      dialogVisible: true,
      initZoom: 0.8,
      categoriesData: [{
        name: '供热关系图',
        color: '#555555',
        size: 60,
        legendIcon: 'react',
        symbol: 'rect'
      }, {
        name: '企业',
        color: '#ee6666',
        size: 50,
        legendIcon: 'rect',
        symbol: 'rect'
      }, {
        name: '热源',
        color: '#91cc75',
        size: 40,
        legendIcon: 'react',
        symbol: 'rect'
      }, {
        name: '换热站',
        color: '#fac858',
        size: 25,
        legendIcon: 'react',
        symbol: 'circle'
      }, {
        name: '供热范围',
        color: '#5470c6',
        size: 15,
        legendIcon: 'circle',
        symbol: 'circle'
      }]
    }
  },
  mounted() {
    this.init();
  },
  unmounted() {
    if (GraphIns) {
      GraphIns.dispose();
    }
  },
  watch: {
  },
  computed: {
  },
  beforeRouteLeave() { },
  methods: {
    init() {
      setTimeout(() => {
        this.doProcessData();
      }, 300)
    },
    doProcessData() {
      const that = this;
      // 构造树
      function buildTree(data) {
        // 创建一个映射表，用于快速查找每个节点
        const map = new Map();
        // 初始化树结构数组
        const tree = [];
        // 遍历数组，将每个节点添加到映射表中
        data.forEach(item => {
          map.set(item.selfID, { ...item, children: [] });
        });
        // 再次遍历数组，构建树结构
        data.forEach(item => {
          const current = map.get(item.selfID);
          if (item.pID === null || !map.has(item.pID)) {
            // 如果 pid 为 null 或未找到父节点，则将当前节点作为根节点
            tree.push(current);
          } else {
            // 否则，找到父节点，并将当前节点添加到父节点的 children 数组中
            const parent = map.get(item.pID);
            parent.children.push(current);
          }
        });
        // 返回构建好的树结构数组
        return tree;
      }
      // 供热范围的数据
      const ALL_DATA_AREA = []
      // 换热站
      const ALL_DATA_HR = []
      // 热源
      const ALL_DATA_RY = []
      // 企业
      const ALL_DATA_EN = []
      // 企业
      function Func4(res) {
        const obj = Object.create(null);
        res.features.forEach(v => {
          const pro = v.properties;
          const DWMC = pro.DWMC
          if (!obj[DWMC]) {
            obj[DWMC] = 1;
          } else {
            obj[DWMC]++
          }
        });
        Object.keys(obj).forEach(v => {
          ALL_DATA_EN.push({
            pID: 'en',
            selfID: v,
            text: v,
          })
        });
        // 合并所有数据
        const ALL_DATA = [...ALL_DATA_AREA, ...ALL_DATA_HR, ...ALL_DATA_RY, ...ALL_DATA_EN];
        // 构建树结构
        let resultTree = buildTree(ALL_DATA);
        resultTree = resultTree.filter(v => { return v.pID === 'en' })
        that.doRender(resultTree)
      }
      // 热源
      function Func3() {
        // 获取换热站的数据
        Api.getDataOfGRZ({
          ids: [],
          // // 换热站名称 热源主键编码
          fields: ['SMID', 'HRZBM', 'ZDMC', 'ZJBM', 'DWMC', 'RYDZ', 'FZR', 'LXFS', 'HRZ_COUNT'],
          attributeFilter: 'SMID > 0'
        }).then(res => {
          const copy = JSON.parse(JSON.stringify(res))
          res.features.forEach((ele, i) => {
            // 自定义 ID
            ele.properties.selfID = ele.properties.ZJBM;
            // 父级 ID 也就是换热站 ID
            ele.properties.pID = ele.properties.DWMC;
            ele.properties.text = ele.properties.ZDMC;
            ALL_DATA_RY.push(ele.properties)
          })
          Func4(copy)
        })
      }
      // 换热站
      function Func2() {
        // 获取换热站的数据
        Api.getDataOfHRZ({
          ids: [],
          // // 换热站名称 热源主键编码
          fields: ['SMID', 'HRZMC', 'ZJBM', 'GRZZJBM', 'RYMC', 'ZDMC', 'XQ_COUNT', 'SFZG'],
          attributeFilter: 'SMID > 0'
        }).then(res => {
          res.features.forEach((ele, i) => {
            // 自定义 ID
            ele.properties.selfID = ele.properties.ZJBM;
            // 父级 ID 也就是换热站 ID
            ele.properties.pID = ele.properties.GRZZJBM;
            ele.properties.text = ele.properties.HRZMC;
            ALL_DATA_HR.push(ele.properties)
          })
          Func3();
        })
      }
      // 供热范围
      function Func1() {
        // 获取供热范围的数据
        Api.getDataOfGRFW({
          ids: [],
          // 区域名称 换热站名称 换热站编码
          fields: ['SMID', 'QYMC', 'HRZMC', 'HRZBM'],
          attributeFilter: 'SMID > 0'
        }).then(res => {
          let temOBJ = Object.create(null);
          res.features.forEach((ele, i) => {
            // 自定义 ID
            ele.properties.selfID = ele.properties.SMID;
            // 父级 ID 也就是换热站 ID
            ele.properties.pID = ele.properties.HRZBM;
            // name 唯一 目前供热的小区存在 name 重复的情况？
            if (temOBJ[ele.properties.QYMC]) {
              temOBJ[ele.properties.QYMC]++
              ele.properties.text = ele.properties.QYMC + temOBJ[ele.properties.QYMC]
            } else {
              temOBJ[ele.properties.QYMC] = 1
              ele.properties.text = ele.properties.QYMC + ' '
            }
            ALL_DATA_AREA.push(ele.properties)
          });
          Func2();
        })
      }
      Func1();

    },
    doRender(allData) {
      //http://ip:8087/api/datacatalog/front/queryDataMap?_=1552964493790
      const getData = [{
        "text": "供热数据图谱",
        "children": allData
      }]

      const categoriesData = this.categoriesData;
      var linksData = [];
      var data = [];

      const colorArr = categoriesData.map(v => {
        return v.color
      })

      function getCategoriesData(obj, size, index) {
        if (obj.children) {
          obj.childSize = obj.children.length
        } else {
          obj.childSize = 0
        }
        if (obj.childSize !== 0) {
          data.push({
            name: obj.text,
            selfID: obj.selfID,
            category: categoriesData[index].name,
            symbolSize: categoriesData[index].size,
            index: index
          });
          for (var i = 0; i < obj.childSize; i++) {
            let child = obj.children[i];
            linksData.push({
              source: obj.text,
              target: child.text
            });
            if (child.children) {
              child.childSize = child.children.length
            } else {
              child.childSize = 0
            }

            if (child.childSize === 0) {
              data.push({
                name: child.text,
                category: categoriesData[index + 1].name,
                index: index + 1,
                // 最小的叶子结点，尺寸是 20
                symbolSize: categoriesData[index + 1].size,
              });
            }
            let childSize = size - 20;
            if (childSize < 20) {
              childSize = 20;
            }
            getCategoriesData(child, childSize, index + 1);
          }
        } else {
        }
      }
      var root = getData[0];
      getCategoriesData(root, 80, 0);

      // console.log(categoriesData)
      // console.log(data)
      // console.log(linksData)

      const option = {
        backgroundColor: 'rgba(4, 30, 60, 1)',
        tooltip: {
          formatter: '{b}'
        },
        legend: {
          itemWidth: 20,
          itemHeight: 10,
          borderRadius: 0,
          itemStyle: {
            borderColor: '#000',
            borderWidth: 1,
          },
          textStyle: {
            color: '#fff',
            fontSize: 15,
            fontFamily: 'ALIBABAPUHUI-REGU'
          },
          data: categoriesData.slice(1).map(v => {
            return {
              name: v.name,
              icon: v.legendIcon,
              itemStyle: {
                color: v.color,
              }
            }
          }),
          selected: {
            '换热站': false,
            '供热范围': false
          }
        },
        animationDuration: 100,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            type: 'graph',
            id: 'self-graph',
            name: 'self-graph',
            legendHoverLink: false,
            roam: true,
            layout: 'force',
            force: {
              repulsion: 1000,
              gravity: 0.1,
              edgeLength: [10, 100],
              layoutAnimation: true,
              friction: 0.6
            },
            edgeSymbol: ['', ''],
            center: ['50%', '50%'],
            zoom: this.initZoom,
            symbolSize: 100,
            focusNodeAdjacency: true,
            draggable: false,
            scaleLimit: {
              min: 0.1,
              max: 5
            },
            categories: categoriesData.map((v, i) => {
              return {
                name: String(v.name),
                symbol: v.symbol
              }
            }),
            animation: false,
            data: data.map(v => {
              return Object.assign(v, {
                name: v.name,
                itemStyle: {
                  color: colorArr[v.index]
                },
                label: {
                  show: v.index >= colorArr.length - 2? false: true,
                  textStyle: {
                    fontSize: 12,
                    fontStyle: '500',
                    fontFamily: 'ALIBABAPUHUI-REGU'
                  },
                  position: 'inside',
                  color: '#fff',
                  textBorderColor: 'inherit',
                  textBorderWidth: 2
                },
              })
            }),
            links: linksData,
            label: {
              show: false,
              textStyle: {
                fontSize: 12,
                fontStyle: '500',
                fontFamily: 'ALIBABAPUHUI-REGU'
              },
              position: 'inside',
              color: '#fff',
              textBorderColor: 'inherit',
              textBorderWidth: 2
            },
            lineStyle: {
              width: 1,
              color: '#999',
              curveness: 0,
              type: "solid"
            },
            expandAndCollapse: true,
            animationDurationUpdate: 50
          },
        ]
      };
      const that = this;
      GraphIns = echarts.init(document.getElementById('Knowledge-map-chart'));
      GraphIns.setOption(option)
      // let categoryStatus = {};
      // let categories = categoriesData.map(v => v.name)
      // 供热站跟供热范围显示的时候，从新调整缩放的级别
      GraphIns.on('legendselectchanged', (params)  => {
        if(params.selected['换热站'] || params.selected['供热范围']) {
          option.series[0].zoom = 0.2;
        } else {
          option.series[0].zoom = this.initZoom;
        }
        option.legend.selected = params.selected;
        GraphIns.setOption(option)
      })
      GraphIns.on('click', function(params) {
        // const currentZoom = GraphIns.getModel()//.getComponent('graph')//.coordinateSystem.getZoom();
        // console.log(currentZoom, 'currentZoom')
        console.log(params, 'params')
        return
        if(zoom) {
          that.initZoom = that.initZoom * zoom;
          if(that.initZoom > 5) {
            that.initZoom = 5
          }
          if(that.initZoom < 0.1) {
            that.initZoom = 0.1
          }
          option.series[0].zoom = that.initZoom;
          if(that.initZoom > 2) {
            option.series[0].label.show = true;
          } else {
            option.series[0].label.show = false;
          }
          // GraphIns.setOption(option)
          console.log(that.initZoom, 'zoom')
        }
      })

      // GraphIns.on('click', function (params) {
      //   let categoryName = params.name;
      //   if (categoryStatus[categoryName]) {
      //     for (let i in categories) {
      //       if (categories[i].includes(params.name) && categories[i] != 'node0') {
      //         GraphIns.dispatchAction({
      //           type: 'legendUnSelect',
      //           name: categories[i]
      //         });
      //       }
      //     }
      //     categoryStatus[categoryName] = false;
      //   } else {
      //     for (let i in categories) {
      //       if (categories[i].includes(params.name) && categoryStatus[categories[i]] || categories[i] === categoryName) {
      //         GraphIns.dispatchAction({
      //           type: 'legendSelect',
      //           name: categories[i]
      //         });
      //       }
      //     }
      //     categoryStatus[categoryName] = true;
      //   }
      // });

    },
    doClose() {
      this.$emit('close')
    }
  }
});
</script>
<template>
  <!-- self-modal-class -->
  <el-dialog modal-class="self-dialog" append-to-body v-model="dialogVisible" top="11rem" width="90%" @close="doClose">
    <template #header>
      <span class="font-alimamashuheiti" style="color: #fff; font-size: 2rem; padding-left: 1rem;">
        供热数据图谱
      </span>
    </template>
    <div id="Knowledge-map-chart">
    </div>
  </el-dialog>
</template>
<style lang="less">
.self-dialog .el-dialog {
  padding-left: 0;
  padding-right: 0;
  background-color: rgba(4, 30, 60, 1);
}
.el-overlay.self-modal-class {
  & .el-dialog {
    background-color: #000;
    background-image: linear-gradient(to right, rgba(4, 30, 60, 0.9), rgba(4, 30, 60, 0.8));
  }

  & .el-dialog__title {
    color: #fff;
  }
}
</style>
<style scoped lang="less">
#Knowledge-map-chart {
  height: 80rem;
  // border: 1px solid tomato;
}
</style>